"""
    @File : redis_tools.py 
    @Create : 2021/11/23 上午11:25 
    @Author : wx
    @Update : 2021/11/23 上午11:25 
    @License : (C)Copyright 2014-2021 SmartAHC All Rights Reserved 
    @Desc    :   Coding Below
    @Software: PyCharm
"""
# 使用到的缓存工具类:
from django.core.cache import cache


class CacheTool():
    def loop_data_update(self, key_item, ser):
        data = cache.get(key_item)
        new_dict = []
        for item in data:
            if item.id == ser.id:
                new_dict.append(ser)
            else:
                new_dict.append(item)
        cache.set(key_item, new_dict, 30)

    def update_cache_data(self, key, ser):
        # 获取该机构下的所有key
        key = key + "*"
        keys = cache.keys(key)
        if len(keys) == 1:
            res01 = cache.get(keys[0])
            new_dict = []
            for item in res01:
                if item.id == ser.id:
                    new_dict.append(ser)
                else:
                    new_dict.append(item)
            cache.set(keys[0], new_dict, 30)

        else:
            for key_item in keys:
                self.loop_data_update(key_item, ser)

    def delete_cache_data(self, key, ser):
        # 获取该机构下的所有key
        key = key + "*"
        keys = cache.keys(key)
        if len(keys) == 1:
            cache_data = cache.get(keys[0])
            new_dict = [item for item in cache_data if item.id != ser.id]
            cache.set(keys[0], new_dict, 30)

        else:
            for key_item in keys:
                self.loop_data_delete(key_item, ser)

    def loop_data_delete(self, key, ser):
        cache_data = cache.get(key)
        new_dict = [item for item in cache_data if item.id != ser.id]
        cache.set(key, new_dict, 30)
